<?php
/**
 * Created by PhpStorm.
 * User: oven
 * Date: 2016/4/12
 * Time: 15:55
 */

class Tools {
    static public function very_mob($mob){
        if(preg_match('/^1[34578]{1}\d{9}$/',$mob)){
            return $mob;
        }else{
            return "";
        }
    }
    
    //小程序登录获取sessionid
    static public function GetThirdsession($len)
    {
        $fp = @fopen('/dev/urandom', 'rb');
    
        $result = '';
    
        if ($fp !== FALSE)
        {
    
            $result .= @fread($fp, $len);
    
            @fclose($fp);
    
        }
        else
        {
            return -1;
        }
    
        $result = base64_encode($result);
    
        $result = strtr($result, '+/', '-_');
    
        return substr($result, 0, $len);
    }
    
    //解密
    static public function DecryptData($appid,$session_key,$encryptedData,$iv)
    {
        if (strlen($session_key) != 24) {
            return -1;
        }
        $aesKey=base64_decode($session_key);
         
        if (strlen($iv) != 24) {
            return -1;
        }
        $aesIV=base64_decode($iv);
         
        $aesCipher=base64_decode($encryptedData);
         
        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj=json_decode($result);
        if( $dataObj  == NULL)
        {
            return -1;
        }
        if( $dataObj->watermark->appid != $appid )
        {
            return -1;
        }
        return $result;
    }
    
    
    /*
     * @param $us 需要得到的key列表
     */
    static public function _get_by_key($us = array()){
        $p = array();
        foreach($us as $key){
            $p[$key] = self::_get($key);
        }
        return $p;
    }

    static public function get_post_json(){
        $post_raw_data = file_get_contents("php://input");
        return json_decode($post_raw_data);
    }
    static public function _get($name,$default="",$param=array()){
        $val = Yii::app()->request->getParam($name,$default);
        if(is_array($val)) return $val;
        if(!$val){
            $json = self::get_post_json();
            $val = @$json->$name;
        }
        $val = trim($val);

        //强制拦截脚本注入的条件
        $val = preg_replace("/(@|update|delete|grant)/i","&nbsp;",$val);

        if(isset($param['prex'])){
            $val = preg_replace($param['prex'],isset($param['prexto']) ? $param['prexto'] : "",$val);
        }
        if(isset($param["format"])  ){
            if("int"== $param["format"]){
                $prex = '/[^\d]/';
            }
            $val = preg_replace($prex,isset($param['prexto']) ? $param['prexto'] : "",$val);
        }


        $val =  str_replace("'","&acute;",$val);
        if(isset($param['secret']) && 1 == $param['secret']){
            $val = self::enaes($val);
        }

        return $val?$val:$default;
    }

    //截取字符串长度
    static  public function sub($str,$len=8){
        if(mb_strlen($str,'utf-8')>$len){
            return mb_substr($str,0,$len-1,'utf-8')."...";
        }
        return $str;
    }
    //截取字符串长度
    static  public function _sub($str,$len=8){
        if(mb_strlen($str,'utf-8') > $len){
            return mb_substr($str,0,$len-1,'utf-8');
        }
        return $str;
    }

    //页面数据调整
    static public function w($str,$key=null,$conv=1,$prex = "",$prexto = ""){
        if($prex){
            $str = preg_replace($prex,$prexto,$str);
        }
        if($conv) {
            $str = str_replace("<", "&lt;", $str);
            $str = str_replace(">", "&gt;", $str);
        }
        if($key){
            $sk = "<span class='skey'>{$key}</span>";
            $str = str_replace($key,$sk,$str);
        }
        return $str;
    }

    //excel表中时间转换
    static public function excel_to_date($days, $time=false){
        $myDateStr ="";
        if(is_numeric($days)){
            $jd = GregorianToJD(1, 1, 1970);
            $gregorian = JDToGregorian($jd+intval($days)-25569);
            $myDate = explode('/',$gregorian);
            $myDateStr = str_pad($myDate[2],4,'0', STR_PAD_LEFT)
                ."-".str_pad($myDate[0],2,'0', STR_PAD_LEFT)
                ."-".str_pad($myDate[1],2,'0', STR_PAD_LEFT)
                .($time?" 00:00:00":'');
        }else{
            $myDateStr = $days;
        }
        return strtotime($myDateStr);
    }


    //记录日志
    static public function rlog($e=null,$msg=null,$page = ""){
        //将补充错误日志文件，暂时未完善
        if($e){
            Yii::log( $e->__toString(), CLogger::LEVEL_ERROR, __CLASS__.'::'.__METHOD__.'('.$e->getLine().')' );
        }

        switch($page){
            case 'page_c':
                echo $msg?$msg."<a href='javascript:;' onclick='layer_close();'>关闭</a>":"";
                break;
            case "page_r":
                echo $msg?$msg."<a href='javascript:;' onclick='history.go(-1);'>返回</a>":"";
                break;
            case "unshow"://不输出
                break;
            default:
                echo $msg?$msg:"";
        }
    }

    /**
     * 用于AES加密
     * @string  $str
     */
    static public function enaes($str){
        $CIPHER = MCRYPT_RIJNDAEL_128;
        $MODE = MCRYPT_MODE_ECB;
        $key =  md5(DXW_INVOTE_SEND_MONEY_KEY,true);
        //$numblock=floor(strlen($str) / 16);
        $pad_len= 16-(strlen($str) % 16);
        $str=str_pad($str, (16*(floor(strlen($str) / 16)+1)), chr($pad_len));
        $encrypted_val=mcrypt_encrypt($CIPHER, $key, $str, $MODE, mcrypt_create_iv( mcrypt_get_iv_size($CIPHER,$MODE), 1));
        return $encrypted_val;
    }

    //获得文件格式
    static public function get_format($format){
        $fmat = $format;
        switch($format){
            case "image/jpeg":
                $fmat = "jpg";
                break;
            case "xls":
                $fmat="xls";
                break;
            case "xlsx":
                $fmat = "xlsx";
                break;
            case "image/png":
                $fmat = "png";
                break;
            case "image/gif":
                $fmat = "gif";
                break;
            case "exe":
                $fmat = "exe";
                break;
        }
        return $fmat;
    }

    //获取上级url地址
    static public function get_refer_router(){
        $refer = $_SERVER['HTTP_REFERER'];
        $prex = '/com\/([a-zA-Z]+)\/([a-zA-Z]+)/i';
        preg_match_all($prex,$refer,$out);
        if(isset($out[2][0])){
            return $out[1][0]."/".$out[2][0];
        }
        return "";
    }

    //图片输出中转
    static public function w_img($path){
        echo DXW_QINIU_URL.'/'.$path;
    }

    static public function Api_Post($url,$param,$method = "POST"){
        if("GET"==$method){
            return  CscHtml::cscPostGet($url,$param,"GET");
        }else{
            return CscHtml::cscPostGet($url,json_encode($param,JSON_UNESCAPED_UNICODE),"POST");
        }
    }

    static public function get_short_url($url=null){
        if(!$url) return "";
        $data["url"] =$url ;
        switch(DXW_DWZ_SOURCE){
            case 'baidu.com':
                $data["url"] =$url ;
                $data["alias"] = "";
                $data["access_type"] = "web";
                $_url = "http://dwz.cn/create.php";
                break;
            case "suo.im":
                $_url = "http://suo.im/front/index/urlCreate/";
                break;
            case "u6.gg":
                $_url = "http://www.ft12.com/create.php?m=index&a=urlCreate";
                $data["type"] =4;
                break;
            case "kks.me":
                $_url = "http://www.ft12.com/create.php?m=index&a=urlCreate";
                $data["type"] =6;
                break;
            case "c7.gg":
                $_url = "http://www.ft12.com/create.php?m=index&a=urlCreate";
                $data["type"] =5;
                break;
            case "rrd.me":
                $_url = "http://www.ft12.com/create.php?m=index&a=urlCreate";
                $data["type"] =1;
                break;
            case "t.cn":
                $_url = "http://www.ft12.com/create.php?m=index&a=urlCreate";
                $data["type"] =7;
                break;
        }
        $json = \Curl::getInstance()->post($_url,$data)->getBody();
        $re =  json_decode($json,true);
        $tinyurl = "";
        switch(DXW_DWZ_SOURCE){
            case "baidu.com":
                $tinyurl = $re["tinyurl"];
                break;
            case "suo.im":
            case "u6.gg":
            case "c7.gg":
            case "rrd.me":
            case "rrd.me":
            case "t.cn":
                $tinyurl =  $re["list"];
                break;
        }
        return $tinyurl;
    }


    static function get_pwd($pwd,$salt=""){
        if(1 == MEMBER_PWD_SALT){
            return md5($pwd.$salt);
        }else{
            return md5($pwd);
        }

    }

    static public function _upload_file_to_local_cache($index="file"){
        if(isset($_FILES[$index]["size"]) && $_FILES[$index]["size"]>0){
            $file_type = $_FILES[$index]["name"];
            $fmts = explode(".",$file_type);
            $fmt = self::get_format($fmts[1]);
            $newname = DXW_CACHE_FILE."/".time().".".$fmt;
            move_uploaded_file($_FILES[$index]["tmp_name"], $newname);
            return array("filename"=>$newname,"fmt"=>$fmt);
        }else{
            return array();
        }
    }

    public static function get_uuid($median  = 3 ){
        $dex = Conf::$rand_str;
        $mt = microtime();
        list($msc, $ts) = explode(" ", $mt);
        $uuid = dechex($ts);
        $tm = date("Z");
        $sign = 0;//时区标志
        if($tm < 0) {
            $sign = 1;
            $tm = abs($tm);
        }
        $tm = intval($tm/3600);//计算时区，
        $uuid .= $sign."".$dex[$tm];
        $ip = $_SERVER["SERVER_ADDR"];//ip地址信息
        $ip = explode(".", $ip);
        $ip = array_map(function($v) {
            $dex = "0123456789abcdef";
            if(isset($v)) {
                $idx = intval($v);
                return "{$dex[($idx>>4)&0xf]}{$dex[$idx&0xf]}";
            } else {return "00";}

        }, $ip);
        foreach($ip as $v) {
            $uuid .= $v;
        }
        $msc = ltrim($msc, "0."); //毫秒
        $uuid .= dechex($msc);

        for($i = 0; $i < $median; $i++) {
            $uuid  .= $dex[rand()&0xf];
        }
        $uuid = mb_substr($uuid,0,8)."-".mb_substr($uuid,9,4)."-".mb_substr($uuid,12,4)."-".mb_substr($uuid,16,-1);
        return $uuid;
    }
    static public function get_session($index){
        return Yii::app()->session->get($index);
    }
    //加密输入字符
    static public function sec($str,$char = "*",$pos ="mid"){
        if(!$str) return '';
        $is_secret = self::get_session("is_secret");
        //2 则显示为明文
        if(2==$is_secret){
            return $str;
        }
        $str = trim($str);
        $len = strlen($str);
        $l = intval($len/3);
        $front = mb_substr($str,0,$l,"utf-8");
        $end = mb_substr($str,strlen($front)+$l,strlen($str),"utf-8");
        $n_c = "";
        for($i=0;$i<$l ;$i++){
            $n_c .= $char;
        }
        return $front.$n_c.$end;
    }

    //随机字符串
    static public function rand_str(){
        $characters  = Conf::$rand_str;
        $str = "";
        for($i=0;$i<Conf::$default_pwd_length;$i++){
            $str .= $characters[mt_rand(0, strlen($characters)-1)];
        }
        return $str;
    }
    static public function w_date($date){
        if(!$date) return;
        $ct = time();
        $t_t  = strtotime(date('Y-m-d'));//今日
        $y_t  = strtotime(date('Y-m-d',strtotime("-1 day")));//昨日
        $y_y_t  = strtotime(date('Y-m-d',strtotime("-2 day")));//前日
        if(($date - $t_t) > 0){
            $sep = abs($date-$ct);
            if(60 >=$sep){
                $str = "{$sep}秒前";
            }elseif(3600 > $sep){
                $str = floor($sep /60)."分钟前";
            }elseif(3600*24 >$sep){
                $str = floor($sep/3600)."小时前";
            }
        }elseif(($date - $y_t) > 0){
            $str =  "昨天". date(" H:i",$date);;
        }elseif(($date - $y_y_t) > 0){
            $str =  "前天". date(" H:i",$date);
        }else{
            $str = date("Y/m/d H:i",$date);
        }
        return $str;
    }
    //数据里面图片抽离
    static public function pull_pics_from_str_away($str,$prex=""){
        $splits = explode('src="',$str);
        $pics = "";
        unset($splits[0]);
        if(count($splits)){
            foreach($splits as $item){
                $pic = Curl::getInstance()->get_html_box('"','"','"'.$item);
                if(!$pic && count($pics) <10) continue;
                $pics .= $pics ? ",".$pic:$pic;
            }
        }
        return $pics;
    }

    //把字符串转换成时间格式
    static public function str_to_date($str){
        $year = substr($str,0,4);
        $month = substr($str,4,2);
        $day = substr($str,6,2);
        $hour = substr($str,8,2);
        $min = substr($str,10,2);
        $sec = substr($str,12,2);
        return $year."-".$month."-".$day." ".$hour.":".$min.":".$sec;
    }

    //时间轴 $min 和$max 统一使用时间戳 并且 max不需要加上当天
    public static function time_axsi($min =null,$max=null,$fmt="m/d"){
        /*
            $min = time()-40*24*3600;
            $max = time()-5*24*3600;
            $data = Tools::time_axsi($min,$max);
        */
        //默认为最近7天数据
        $data = [];
        if(!$max && !$min){
            for($i=Conf::$time_axsi_len-1;$i>=0;$i--){
                $data[] = date($fmt,strtotime("-{$i} day"));
            }
        }elseif($max && $min ){
            $i=0;
            while(true){
                $sep = $i*3600*24;
                $i++;
                $rdu_time  = $min+$sep;
                if($rdu_time > $max){
                    break;
                }
                $data[] = date($fmt,$rdu_time);
            }
        }
        return $data;
    }
    public static function ch_to_unicode($name){
        $name = iconv('UTF-8', 'UCS-2', $name);
        $len = strlen($name);
        $str = '';
        for ($i = 0; $i < $len - 1; $i = $i + 2){
            $c = $name[$i];
            $c2 = $name[$i + 1];
            if (ord($c) > 0){   //两个字节的文字
                $str .= '\u'.base_convert(ord($c), 10, 16).str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
            }
            else{
                $str .= $c2;
            }
        }
        return $str;
    }
}